<template>
  <view>
    <!-- 规格-模态层弹窗 -->
    <!-- @touchmove.stop.prevent="stopBubble" -->
    <view
	  catchtouchmove="true"	
      class="popup spec"
      :class="specClass"
      @click="toggleSpec"
    >
      <!-- 遮罩层 -->
      <view class="mask">
        <view
          class="layer spec-content-box"
          @click.stop="stopBubble"
        >
          <view class="spec-content">
            <view class="a-t">
              <image
                @click.stop="previewImage([`${privateGoodsDetail.imagePath}`],
              0)"
                class="img"
                :src="privateGoodsDetail.imagePath"
              ></image>
              <view class="right">

                <!-- 价格 begin -->
                <view
                  :style="themeStyles.textMainColor"
                  class="price-box"
                  >
                  <template v-if="!isChooseSpec">
                    <text class="price">{{privateGoodsDetail.minPrice[0]}}</text>
                    <text class="decimal">{{privateGoodsDetail.minPrice[1] || '00'}}</text>
                    <template v-if="privateGoodsDetail.maxPrice.length">
                      -
                      <text class="price">{{privateGoodsDetail.maxPrice[0]}}</text>
                      <text class="decimal">{{privateGoodsDetail.maxPrice[1] || '00'}}</text>
                    </template>
                  </template>
                  <template v-else>
                    <text class="price">{{privateGoodsDetail.specPrice[0]}}</text>
                    <text class="decimal">{{privateGoodsDetail.specPrice[1] || '00'}}</text>
                  </template>
                </view>
                <!-- 价格 end -->

                <view class="stock">库存：{{privateGoodsDetail.stock || '暂无库存'}}</view>
                <view
                  v-if="privateGoodsDetail.isMoreSpec"
                  class="selected"
                >
                  <text v-if="isChooseSpec">
                    <text class="spec-title">已选：</text>
                    <text class="selected-text">{{privateGoodsDetail.valueNames}} </text>
                  </text>
                  <text
                    v-else
                    class="spec-title"
                  >请选择规格</text>
                </view>
              </view>
            </view>
            <!-- 规格 begin -->
            <view
              v-for="(item, index) in privateGoodsDetail.specsKeyList"
              :key="index"
              class="spec-list"
				      >
              <text class="spec-title">{{item.specsKey}}</text>
              <view class="item-list">
                <!-- 主题色 -->
                <text
                  v-for="(childItem, childIndex) in item.specsValueList"
                  :key="childIndex"
                  class="tit"
                  :class="{ selected: childItem.selected }"
                  :style="childItem.selected && themeStyles.btnGhostColor"
                  @click="selectSpec(childIndex, index)"
                >
                  {{childItem.specsValue}}
                </text>
              </view>
            </view>
            <!-- 规格 end -->
            <!-- 购买数量 begin -->
            <view
              v-if="noSpec || (isChooseSpec && privateGoodsDetail.stock)"
              class="df jc-sb buy-num-wrap"
              >
              <text class="title">购买数量</text>
              <view class="df df-r number">
                <view
                  class="tac sub"
                  @tap.stop="onChangeBuyNum('sub')"
                >-</view>
                <view class="df df-c input-box">
                  <input
                    disabled
                    class="tac input"
                    type="number"
                    v-model="buyNum"
                    @input="onChangeBuyNum('sum')"
                  />
                </view>
                <view
                  class="tac add"
                  @tap.stop="onChangeBuyNum('add')"
                >+</view>
              </view>
            </view>
            <!-- 购买数量 end -->
          </view>
          <!-- 操作按钮 begin -->
          <template v-if="noSpec || isChooseSpec">
            <slot name="btnGroup">
              <view class="btn-group">
                <template v-if="privateGoodsDetail.stock">
                  <view
                    v-if="actionBuyType === 3"
                    class="df df-r"
                  >
                    <button
                      @click.stop="addGoodsToCart()"
                      :style="themeStyles.btnLightAuxiliaryColor"
                      class="df1 btn-s add-cart-btn"
                    >加入购物车</button>
                    <button
                      @click.stop="nowBuy()"
                      :style="themeStyles.btnFullColor"
                      class="df1 btn-s now-buy-btn"
                    >立即购买</button>
                  </view>
                  <button
                    v-else
                    @click.stop="confirmActionBuy()"
                    :style="themeStyles.btnFullColor"
                    class="btn"
                  >确定</button>
                </template>
                <template v-else>
                  <button
                    class="btn"
                    @click.stop="cancel()"
                  >取消</button>
                </template>
              </view>
            </slot>
          </template>
          <!-- 操作按钮 end -->
        </view>
      </view>
    </view>

  </view>
</template>

<script>
import { baseFileUri } from "@/utils/request/baseConfig";

import { mapState, mapMutations } from "vuex";
export default {
  props: {
    // 
    goodsDetail: {
      type: Object,
      default() {
        return {};
      }
    },
    // 
    specClass: {
      type: String,
      default: "none"
    },

    // 0: 添加购物车; 1: 立即购买; 2: 改变当前购物车商品规格; 3: 单独购买活动商品; 4: 活动商品
    actionBuyType: {
      type: Number,
      default: 0
    },

    // 根据状态值展示商品价格 1101: 普通商品 2101: 活动商品
    showPriceStatus: {
      type: String,
      default: "1011"
    }
  },

  data() {
    return {
      currentSpecsValue: "",
      noSpec: false, // 木有商品规格信息???
      imagePath: "",
      baseFileUri,
      privateGoodsDetail: null,  //商品详情
      currentSpec: null,  //
      specSelected: null,  //
      isChooseSpec: false,  //是否已选择规格
      buyNum: 1, //
      oldShowPriceStatus: null  // 根据状态值展示商品价格 1101: 普通商品 2101: 活动商品
    };
  },

  computed: {
    ...mapState("activity", ["activityData"])
  },

  watch: {
    goodsDetail: {
      handler: function(val, oldVal) {
        if (!val) return;
        console.log("选择商品规格---val", val);
        if (
          this.oldShowPriceStatus &&
          this.showPriceStatus == this.oldShowPriceStatus
        ) {
          return;
        }
        this.oldShowPriceStatus = this.showPriceStatus;
        // 商品信息
        this.privateGoodsDetail = JSON.parse(JSON.stringify(val));
        this.isChooseSpec = false;
        this.buyNum = 1;
        this.noSpec = val.specsKeyList.length === 0;
        this.currentSpec = null;  
        this.specSelected = null; //
      },
      deep: true
    }
  },

  methods: {
    toggleSpec() {
      this.$emit("toggleSpec");
    },

    // 根据传参类型展示商品价格
    handleCurrentPrice(currentSpec, showPriceStatus) {
      let price = [];

      if (showPriceStatus === "2101") {
        price = `${currentSpec.activityPrice}`.split(".");
      } else {
        price = `${currentSpec.price}`.split(".");
      }
      return price;
    },

    //选择规格
    async selectSpec(childIndex, index) {
      const specsValueList = this.privateGoodsDetail.specsKeyList[index]
        .specsValueList;
      //
      //console.log("specsValueList---",specsValueList);
      for (const value of specsValueList) {
        this.$set(value, "selected", false);
      }
      this.$set(specsValueList[childIndex], "selected", true);

      const list = this.privateGoodsDetail.specsKeyList;

      //选择的规格存放在specSelected中
      this.specSelected = [];
      list.forEach(item => {
        item.specsValueList.forEach(childItem => {
          if (childItem.selected) {
            this.specSelected.push(childItem);
          }
        });
      });
      //
      //console.log("specSelected---",this.specSelected);
      // 判断是否选了规格
      if (this.specSelected.length === list.length) {
        this.isChooseSpec = true;
        this.analyzeSpec(this.specSelected);
      } else {
        this.isChooseSpec = false;
      }

      this.$emit("onSelectSpec", this.privateGoodsDetail);
    },

    // 规格详情
    analyzeSpec(specSelected = []) {
      const goods = this.privateGoodsDetail;
      let valueIdArray = [];
      let valueNamesArr = [];
      let currentSpec = [];   // 所选规格对应的商品sku信息
      for (const item of specSelected) {
        valueIdArray.push(item.specsValueId);
        valueNamesArr.push(item.specsValue);
      }

      for (const sku of goods.skuList) {
        if (sku.specsValueList === valueIdArray.join()) {
          currentSpec = sku;
        }
      }

      goods.valueNames = valueNamesArr.join();

      // 当前规格图片
      goods.imagePath =
        this.baseFileUri + (currentSpec.imagePath || goods.imagePathMain[0]);

      // 当前规格库存
      goods.stock = currentSpec.stock;

      // 当前规格id
      goods.skuId = currentSpec.skuId;

      // 当前规格价格
      goods.specPrice = this.handleCurrentPrice(
        currentSpec,
        this.showPriceStatus
      );
    },

    // 改变购买数量
    onChangeBuyNum(type) {
      // 活动数量固定一个
      if (this.actionBuyType === 4) {
        this.buyNum = 1;
        this.$api.showToast("活动商品只能购买一个哦~");
        return;
      }

      // 最大购买数量
      if (this.buyNum > this.privateGoodsDetail.stock) {
        setTimeout(() => {
          this.buyNum = this.privateGoodsDetail.stock;
        }, 0);
      }

      // 最小购买数量
      if (this.buyNum < 1) {
        setTimeout(() => {
          this.buyNum = 1;
        }, 0);
      }

      if (type == "sub") {
        this.buyNum > 1
          ? this.buyNum--
          : this.$api.showToast("不能再少了 * _ *");
      } else if (type == "add") {
        this.buyNum < this.privateGoodsDetail.stock
          ? this.buyNum++
          : this.$api.showToast("没有更多了 * _ *");
      }
    },

    // 直接结算 OR 加入购物车
    async confirmActionBuy() {
      if (!this.validator()) {
        return;
      }

      if (this.actionBuyType === 0) {
        this.addGoodsToCart();
      } else if (this.actionBuyType === 1 || this.actionBuyType === 4) {
        this.nowBuy();
      } else {
        this.cancel();
      }
    },

    // 立即购买
    nowBuy() {
      //
      const joinActivity = this.showPriceStatus === "2101"; 

      // buyData待优化（使用vuex）
      const buyData = {
        goodsId: this.privateGoodsDetail.goodsId,
        skuId: this.privateGoodsDetail.skuId || "",
        actType: (joinActivity && this.privateGoodsDetail.activityType) || "",
        actId: (joinActivity && this.privateGoodsDetail.activityId) || "",
        num: this.buyNum || ""
      };

      this.$emit("onNowBuy", buyData);
    },

    // 添加到购物车
    addGoodsToCart() {
      const skuId = this.privateGoodsDetail.skuId;

      const buyData = {
        skuId,
        number: this.buyNum
      };
      this.$emit("onAddGoodsToCart", buyData);
    },

    // 取消
    cancel() {
      this.toggleSpec();
      this.$emit("onCancel");
    },

    // 规格验证器
    validator() {
      if (this.privateGoodsDetail.isMoreSpec && !this.isChooseSpec) {
        this.$api.showToast("请选择规格");
        return false;
      }

      if (!this.privateGoodsDetail.stock) {
        this.$api.showToast("暂无库存");
        return false;
      }

      return true;
    }
  }
};
</script>

<style lang="scss" scoped>
@import "@/common/styles/goods/spec.scss";
.popup {
  .btn-group {
    z-index: 99;
    position: absolute;
    // margin-top: 126rpx;
    background-color: $theme-panel-bg-color;
    bottom: 0;
    left: 24rpx;
    right: 24rpx;
    height: calc(100rpx + var(--safe-area-inset-bottom));
    font-size: $theme-size-large-base;
    .btn {
      height: 80rpx;
      line-height: 80rpx;
      border-radius: 200rpx;
      color: $theme-color-main-base;
    }

    .btn-s {
      border-radius: 0;
      height: 80rpx;
      line-height: 80rpx;
    }

    .add-cart-btn {
      border-radius: 200rpx 0 0 200rpx;
    }

    .now-buy-btn {
      border-radius: 0 200rpx 200rpx 0;
    }
  }
}
</style>
